package org.zheng.shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.zheng.shop.dto.CompanyNewsDTO;
import org.zheng.shop.security.UserDetailsImpl;
import org.zheng.shop.service.CompanyNewsService;

import java.util.List;
import java.util.Map;

/**
 * 企业动态控制器
 */
@RestController
@RequestMapping("/api/news")
@CrossOrigin(origins = "*", maxAge = 3600)
public class CompanyNewsController {

    @Autowired
    private CompanyNewsService newsService;

    /**
     * 获取可见的动态列表（公开接口）
     */
    @GetMapping
    public ResponseEntity<?> getVisibleNews(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<CompanyNewsDTO> newsPage = newsService.getVisibleNews(page, size);
            return ResponseEntity.ok(newsPage);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取动态列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取动态详情（公开接口）
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getNewsById(@PathVariable Long id) {
        try {
            CompanyNewsDTO news = newsService.getNewsById(id, false);
            
            // 增加浏览次数
            newsService.incrementViewCount(id);
            
            return ResponseEntity.ok(news);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取动态详情失败: " + e.getMessage()));
        }
    }

    /**
     * 搜索动态（公开接口）
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchNews(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<CompanyNewsDTO> newsPage = newsService.searchNews(keyword, page, size, false);
            return ResponseEntity.ok(newsPage);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "搜索动态失败: " + e.getMessage()));
        }
    }

    /**
     * 获取最新动态（公开接口）
     */
    @GetMapping("/latest")
    public ResponseEntity<?> getLatestNews(@RequestParam(defaultValue = "5") int limit) {
        try {
            List<CompanyNewsDTO> newsList = newsService.getLatestNews(limit);
            return ResponseEntity.ok(newsList);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取最新动态失败: " + e.getMessage()));
        }
    }

    /**
     * 获取置顶动态（公开接口）
     */
    @GetMapping("/pinned")
    public ResponseEntity<?> getPinnedNews() {
        try {
            List<CompanyNewsDTO> newsList = newsService.getPinnedNews();
            return ResponseEntity.ok(newsList);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取置顶动态失败: " + e.getMessage()));
        }
    }

    // ==================== 管理员接口 ====================

    /**
     * 管理员获取所有动态列表
     */
    @GetMapping("/admin/all")
    public ResponseEntity<?> getAllNews(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            Page<CompanyNewsDTO> newsPage = newsService.getAllNews(page, size);
            return ResponseEntity.ok(newsPage);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取动态列表失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员根据ID获取动态详情
     */
    @GetMapping("/admin/{id}")
    public ResponseEntity<?> getNewsByIdForAdmin(@PathVariable Long id, Authentication authentication) {
        try {
            CompanyNewsDTO news = newsService.getNewsById(id, true);
            return ResponseEntity.ok(news);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取动态详情失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员搜索动态
     */
    @GetMapping("/admin/search")
    public ResponseEntity<?> searchNewsForAdmin(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            Page<CompanyNewsDTO> newsPage = newsService.searchNews(keyword, page, size, true);
            return ResponseEntity.ok(newsPage);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "搜索动态失败: " + e.getMessage()));
        }
    }

    /**
     * 创建动态
     */
    @PostMapping("/admin")
    public ResponseEntity<?> createNews(@RequestBody CompanyNewsDTO newsDTO, Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            CompanyNewsDTO createdNews = newsService.createNews(newsDTO, userDetails.getId());
            return ResponseEntity.ok(createdNews);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "创建动态失败: " + e.getMessage()));
        }
    }

    /**
     * 更新动态
     */
    @PutMapping("/admin/{id}")
    public ResponseEntity<?> updateNews(@PathVariable Long id, @RequestBody CompanyNewsDTO newsDTO, 
                                      Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            CompanyNewsDTO updatedNews = newsService.updateNews(id, newsDTO, userDetails.getId());
            return ResponseEntity.ok(updatedNews);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "更新动态失败: " + e.getMessage()));
        }
    }

    /**
     * 删除动态
     */
    @DeleteMapping("/admin/{id}")
    public ResponseEntity<?> deleteNews(@PathVariable Long id, Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            newsService.deleteNews(id, userDetails.getId());
            return ResponseEntity.ok(Map.of("message", "动态删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "删除动态失败: " + e.getMessage()));
        }
    }

    /**
     * 切换动态可见性
     */
    @PostMapping("/admin/{id}/toggle-visibility")
    public ResponseEntity<?> toggleVisibility(@PathVariable Long id, Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            CompanyNewsDTO updatedNews = newsService.toggleVisibility(id, userDetails.getId());
            return ResponseEntity.ok(updatedNews);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "切换可见性失败: " + e.getMessage()));
        }
    }

    /**
     * 切换置顶状态
     */
    @PostMapping("/admin/{id}/toggle-pin")
    public ResponseEntity<?> togglePin(@PathVariable Long id, Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            CompanyNewsDTO updatedNews = newsService.togglePin(id, userDetails.getId());
            return ResponseEntity.ok(updatedNews);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "切换置顶状态失败: " + e.getMessage()));
        }
    }
}
